//
//  PzPhotoCtrl.swift
//  Pz
//
//  Created by 蓝鳍互娱 on 2024/6/26.
//

import Foundation
import UIKit
import XHToastSwift
import Photos
class PzPhotoCtrl: UIViewController {
    var photoSubMdl:PzPhotoSubModel?{
        didSet{
            photoNavTitleLab.text = photoSubMdl?.name
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.navigationBar.isHidden = true
        view.backgroundColor = .clear
        creatSubView()
    }
    lazy var photoBgImgView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "pzHomeBg")
        return imageView
    }()
    lazy var photoNavBackBtn: UIButton = {
        let btn = UIButton()
        btn.addTarget(self, action: #selector(vipNavBack), for: .touchUpInside)
        btn.setBackgroundImage(UIImage(named: "pzNavBackIcon"), for: .normal)
        return btn
    }()
    lazy var photoNavTitleLab: UILabel = {
        let lab = UILabel()
        lab.font = UIFont.systemFont(ofSize: 34.fitScale(), weight: .regular)
        lab.textColor = UIColor(hex:0xFFFFFF)
        return lab
    }()
    lazy var photoBottomView: PzPhotoBottomView = {
        let view = PzPhotoBottomView()
        return view
    }()
    lazy var defPhotoView: PzDefPhotoView = {
        let view = PzDefPhotoView(frame: CGRect(x: 0.fitScale(), y: 176.fitScale(), width: PzPublicConst.ScreenWidth, height: PzPublicConst.ScreenHeight - 498.fitScale()))
        return view
    }()
    
    
    func creatSubView(){
        self.view.addSubview(photoBgImgView)
        self.view.addSubview(photoNavBackBtn)
        self.view.addSubview(photoNavTitleLab)
        self.view.addSubview(photoBottomView)
        self.view.addSubview(defPhotoView)


        photoBgImgView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        photoNavBackBtn.snp.makeConstraints { make in
            make.left.equalTo(24.fitScale())
            make.top.equalTo(PzPublicConst.ScreenTopSpaceHeight + 12.fitScale())
            make.width.height.equalTo(64.fitScale())
        }
        photoNavTitleLab.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(photoNavBackBtn)
            make.height.equalTo(50.fitScale())
        }
        photoBottomView.snp.makeConstraints { make in
            make.left.equalTo(0.fitScale())
            make.right.equalTo(0.fitScale())
            make.bottom.equalTo(0.fitScale())
            make.height.equalTo(322.fitScale())
        }
        photoBottomView.photoAumBlock = {
            self.checkCameraAumLimit { completion in
                if completion{
                   let imagePickCtrl = TZImagePickerController(maxImagesCount: 1, delegate: self)
                    imagePickCtrl?.showSelectBtn = false
                    imagePickCtrl?.allowCrop = false
                    imagePickCtrl?.cropRect = self.defPhotoView.frame
                    imagePickCtrl?.allowPickingGif = false
                    imagePickCtrl?.allowPickingVideo = false
                    imagePickCtrl?.modalPresentationStyle = .fullScreen
                    self.navigationController?.present(imagePickCtrl!, animated: true)
                }
            }
        }
        photoBottomView.photoBlock = {
            self.defPhotoView.talkCam()
        }
        photoBottomView.photoChangeBlock = {
            self.defPhotoView.changeCam()
        }
//        defPhotoView.snp.makeConstraints { make in
//            make.left.equalTo(0.fitScale())
//            make.right.equalTo(0.fitScale())
//            make.top.equalTo(176.fitScale())
//            make.height.equalTo(PzPublicConst.ScreenHeight - 498.fitScale())
//        }
        defPhotoView.photoSubMdl = photoSubMdl
        defPhotoView.photoBase64Block = { baseImg in
            self.requestCheckFace(base64: baseImg)
        }
    }
    func requestCheckFace(base64:String?){
        if base64 != nil{
            MBProgressHUD.showAdded(to: self.view, animated: true)
            let parameters = ["base64":base64!]
            PzNetHttp.defaultRequest().post(PzPublicConst.photoLiveFaceUrl, param: parameters) { data in
                let jsonDict:NSDictionary = data as! NSDictionary
                let code:Int = jsonDict["code"] as! Int
                if code > 40{
                    self.requestCheckKouTu(base64: base64)
                }else{
                    XHToast.showCenterWithText("人脸识别失败")
                    self.defPhotoView.resetCam()
                    MBProgressHUD.hide(for: self.view, animated: true)
                }
            } fail: { error in
                MBProgressHUD.hide(for: self.view, animated: true)
            }
        }
    }
    func requestCheckKouTu(base64:String?){
        if base64 != nil{
            let parameters = ["base64":base64!]
            PzNetHttp.defaultRequest().post(PzPublicConst.photoLiveKoutuUrl, param: parameters) { data in
                let jsonDict:NSDictionary = data as! NSDictionary
                let code:Int = jsonDict["code"] as! Int
                if code > 40{
                    let dataStr:String = jsonDict["data"] as! String
                    self.requestCheckUpload(base64: dataStr)
                }else{
                    XHToast.showCenterWithText("人脸识别失败")
                    self.defPhotoView.resetCam()
                    MBProgressHUD.hide(for: self.view, animated: true)
                }
            } fail: { error in
                MBProgressHUD.hide(for: self.view, animated: true)
            }
        }
    }
    func requestCheckUpload(base64:String?){
        if base64 != nil{
            let baseFile = PzPublicConst.photoLiveSaveUrl + base64!
            let json:NSDictionary = ["name":photoSubMdl?.name ?? "","bgIndex":photoSubMdl?.bgIndex ?? "","specs1":photoSubMdl?.specs1 ?? "","specs2":photoSubMdl?.specs2 ?? ""]
            let parameters = ["file":baseFile,"udid":UIDevice.current.identifierForVendor?.uuidString ?? "","fileName":"yao1234","size":"yao1234","time":"yao1234","fnType":json.mj_JSONString()] as [String : Any]
            PzNetHttp.defaultRequest().post(PzPublicConst.photoLiveUploadUrl, param: parameters) { data in
                let jsonDict:NSDictionary = data as! NSDictionary
                let code:Int = jsonDict["code"] as! Int
                if code > 40{
                    let dataDic:NSDictionary = jsonDict["data"] as! NSDictionary
                    let dataId:String = dataDic["id"] as! String
                    let url:String = PzPublicConst.photoLiveEditUrl
                    let dataUrl = url.replacingOccurrences(of:"%@", with: dataId)
                    
                   let webCtrl = PzWebCtrl()
                    webCtrl.webUrl = dataUrl
                    webCtrl.isHiddenBack = true
                    self.navigationController?.pushViewController(webCtrl, animated: true)
                }else{
                    XHToast.showCenterWithText("人脸识别失败")
                    self.defPhotoView.resetCam()
                }
                MBProgressHUD.hide(for: self.view, animated: true)
            } fail: { error in
                MBProgressHUD.hide(for: self.view, animated: true)
            }
        }
    }
    @objc func vipNavBack(){
        self.navigationController?.popViewController(animated: true)
    }
    func checkCameraAumLimit(_ completion: @escaping (Bool) -> Void){
        let camAumAuthStatus = PHPhotoLibrary.authorizationStatus()
        if camAumAuthStatus == .authorized{
            DispatchQueue.main.async() {
                completion(true)
            }
        }else if camAumAuthStatus == .notDetermined{
            PHPhotoLibrary.requestAuthorization { status in
                if status == .authorized{
                    DispatchQueue.main.async() {
                        completion(true)
                    }
                }else{
                    let alertCtrl = UIAlertController(title: "提示", message: "相册权限已关闭，请前往设置中打开权限", preferredStyle: .alert)
                    alertCtrl.addAction(UIAlertAction(title: "好的", style: .cancel, handler: { action in
                        DispatchQueue.main.async() {
                            completion(false)
                        }
                    }))
                    alertCtrl.addAction(UIAlertAction(title: "设置", style: .default, handler: { action in
                        if let settingUrl = URL(string: UIApplication.openSettingsURLString){
                            if UIApplication.shared.canOpenURL(settingUrl) {
                                UIApplication.shared.open(settingUrl)
                            }
                        }
                    }))
                    UIApplication.shared.delegate?.window??.rootViewController?.present(alertCtrl, animated: true)
                }
            }
        }else{
            let alertCtrl = UIAlertController(title: "提示", message: "相册权限已关闭，请前往设置中打开权限", preferredStyle: .alert)
            alertCtrl.addAction(UIAlertAction(title: "好的", style: .cancel, handler: { action in
                DispatchQueue.main.async() {
                    completion(false)
                }
            }))
            alertCtrl.addAction(UIAlertAction(title: "设置", style: .default, handler: { action in
                if let settingUrl = URL(string: UIApplication.openSettingsURLString){
                    if UIApplication.shared.canOpenURL(settingUrl) {
                        UIApplication.shared.open(settingUrl)
                    }
                }
            }))
            UIApplication.shared.delegate?.window??.rootViewController?.present(alertCtrl, animated: true)
        }
    }
    func cutImg(image:UIImage,size:CGSize) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        image.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        guard let sizeImage = UIGraphicsGetImageFromCurrentImageContext() else { return UIImage() }
        UIGraphicsEndImageContext()
        return sizeImage
    }
}
extension PzPhotoCtrl:TZImagePickerControllerDelegate{
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool) {
        let photo = photos.first
        
        let photows = photoSubMdl?.specs1?.components(separatedBy: " x ")
        let phtotohs = photows?.last?.components(separatedBy: "px")
        guard let imgW = Float(photows?.first ?? "0") else { return }
        guard let imgH = Float(phtotohs?.first ?? "0") else { return  }
        let redio = Float(imgH)/Float(imgW)
        if photoSubMdl != nil{
            let cutImg = cutImg(image: photo!, size: CGSize(width: 307, height: 307.0*Double(redio)))
            defPhotoView.photoImgView.image = cutImg
            let imgData = cutImg.jpegData(compressionQuality: 0.5)
            let base64Img = imgData?.base64EncodedString(options: .lineLength64Characters)
            requestCheckFace(base64: base64Img)
        }
    }
}
